<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="main-content">
          <div class="form-box">
            <BasicForm @register="registerForm">
              <template #slotBtns>
                <div class="btn-box page-form-slotbtn">
                  <a-button
                    class="btn-box-item"
                    type="primary"
                    style="margin-right: 10px"
                    @click="readParams"
                    >读取参数</a-button
                  >
                  <a-button class="btn-box-item" type="primary" style="margin-right: 10px" @click="handleDownLoad"
                    >导出参数</a-button
                  >
                  <a-button class="btn-box-item" type="primary" style="margin-right: 10px" @click="handleImport"
                    >导入参数</a-button
                  >
                  <a-button
                    class="btn-box-item"
                    type="primary"
                    style="margin-right: 10px"
                    @click="parameterIssued"
                    >参数下发</a-button
                  >
                  <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
                </div>
              </template>
            </BasicForm>
          </div>
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :clickToRowSelect="false"
            :showIndexColumn="true"
            :striped="true"
            :bordered="true"
            :pagination="false"
            rowKey="key"
          >
            <template #bodyCell="{ column, record }">
              <!-- 写入质量值NG红色OK绿色 -->
              <template v-if="column.key === 'WriteQuality'">
                <span :class="record[column.key] === 'NG' ? 'red' : 'green'">
                  {{ record[column.key] }}
                </span>
              </template>
              <!-- 写入后读取值跟写入值一致是蓝色，否则灰色 -->
              <template v-if="column.key === 'ReadValue'">
                <span :class="record[column.key] == record['WriteValue'] ? 'blue' : 'red'">
                  {{ record[column.key] }}
                </span>
              </template>
              <template v-if="column.key === 'ReadTimeStamp'">
                <span  :class="record[column.key] == record['WriteValue'] ? 'blue' : 'red'">
                  {{ record[column.key] }}
                </span>
              </template>
              <template v-if="column.key === 'WriteValue'">
                <a-input
                  type="text"
                  v-model:value="record[column.key]"
                  @blur="onInputBlur(record)"
                />
              </template>
            </template>
          </BasicTable>
        </div>
        <!-- 上传Excel -->
      <uploadExcel
        @register="registerByUpload"
        :classParams="['SuperX.DeviceService.CommandDownload.DownloadTag,SuperX.DeviceService']"
        :uploadParams="{
          ...uploadParams,
          model: 'SuperX.DeviceService.CommandDownload.DownloadTag,SuperX.DeviceService',
          sheetIndex: '-1',
          headRow: '0',
        }"
        @success="handleUploadSuccess"
      />
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  // eslint-disable-next-line
  import { ref, onMounted, reactive, h, unref, nextTick } from 'vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Pagination } from 'ant-design-vue';
  import { getdevicetypes } from '/@/api/equipmentType/index';
  import { getdevicemodels, getdatalist } from '/@/api/equipmentModel/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getalarmrecord, changealarmstatus } from '/@/api/alertRules/index';
  import { downloadByData, getFileHash } from '/@/utils/file/download';
  import { useModal } from '/@/components/Modal';
  import uploadExcel from '/@/views/project/equipmentControl/components/uploadExcel/index.vue';
  import {
    getequipmentinfo,
    readdownloadtags,
    commanddownload,
    afterdownloadinfo,
    handledownLoad,
    mergedata
  } from '/@/api/equipmentControl/index';
  import dayjs from 'dayjs';
  import { useGo } from '/@/hooks/web/usePage';
  import { Console } from 'console';

  const go = useGo();
  const APagination = Pagination;
  let loading = ref(false);
  let tableData = reactive([]);
  // 设备类型
  let deviceTypeList = [];
  // 设备型号
  let deviceModelList = [];
  // 设备类别
  let CategoryObj = [];
  //设备编码
  let driverinfoList = ref([]) as any;
  let uploadParams = reactive({
    Parameters: '[]',
    Controller: 'CmdDownload',
    Action: 'FileImport',
  });

  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  const { hasPermission } = usePermission();
  const { createConfirm, createMessage } = useMessage();
  const [registerByUpload, { openModal: openModalByupload, closeModal: closeModalByupload }] =
  useModal();
  //报警级别颜色
  const levelColorObj = {
    提示: '#3399CC',
    轻微: '#33CCCC',
    一般: '#FFCC00',
    严重: '#FF9999',
    紧急: '#993399',
  };

  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'TypeCode',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 4,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
        onChange: (e) => {
          nextTick(() => {
            getDriverinfo();
          });
        },
      },
    },
    {
      field: 'ModelCode',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 4,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
        onChange: (e) => {
          nextTick(() => {
            getDriverinfo();
          });
        },
      },
    },

    {
      label: '设备编码',
      field: 'AssetCode',
      component: 'ApiSelect',
      colProps: {
        span: 4,
      },
      componentProps: {
        options: [],
        onChange: (e) => {
          console.log(driverinfoList.value);
          let result = driverinfoList.value.filter((item) => item.AssetCode.includes(e));
          setFieldsValue({ DeviceName: result[0].FullName });
        },
      },

      required: true,
    },
    {
      field: 'DeviceName',
      component: 'Input',
      label: '设备名称：',
      colProps: {
        span: 4,
      },
      componentProps: {
        disabled: true,
      },
    },
    {
      field: 'btns',
      component: 'Input',
      label: '',
      slot: 'slotBtns',
      colProps: {
        span: 8,
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, updateSchema, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { t } = useI18n();
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });

  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '变量',
      dataIndex: 'Name',
    },
    {
      title: '数量类型',
      dataIndex: 'DataType',
    },
    {
      title: '当前值',
      dataIndex: 'Value',
      width: 100,
    },
    {
      title: '写入值',
      dataIndex: 'WriteValue',
    },
    {
      title: '写入质量数',
      dataIndex: 'WriteQuality',
    },
    {
      title: '下发时间戳',
      dataIndex: 'WriteTimeStamp',
      width: 180,
    },
    {
      title: '写入后读取值',
      dataIndex: 'ReadValue',
    },
    {
      title: '时间戳',
      dataIndex: 'ReadTimeStamp',
      width: 180,
    },
    {
      title: '单位',
      dataIndex: 'Unit',
    },

    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];

  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  // 获取设备类型
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getdevicetypes([
        {
          PageNO: 1,
          PageSize: 500,
        },
      ]);
      deviceTypeList = res.Rows;
      updateSchema({
        field: 'TypeCode',
        componentProps: {
          options: deviceTypeList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //获取设备编码列表
  async function getDriverinfo() {
    const { TypeCode, ModelCode, AssetCode } = await getFieldsValue();
    try {
      loading.value = true;
      let params = {
        AssetCode: '',
        TypeCode: TypeCode, // 设备类型
        ModelCode: ModelCode, // 设备型号
      };
      let res = await getequipmentinfo([params]);
      if (res) {
        driverinfoList.value = res;
        updateSchema({
          field: 'AssetCode',
          componentProps: {
            options: res.map((item) => {
              return {
                label: item.AssetCode,
                value: item.AssetCode,
              };
            }),
          },
        });
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取设备型号
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          PageSize: 50,
        },
      ]);
      deviceModelList = res.Rows;

      updateSchema({
        field: 'ModelCode',
        componentProps: {
          options: deviceModelList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 重置按钮点击事件
  async function handleResetFields() {
    initSearch();
    // getTableData();
  }
  // 重置搜索条件
  function initSearch() {
    setFieldsValue({
      TypeCode: '',
      ModelCode: '',
      AssetCode: '',
      FullName: '',
    });
    tableData = [];
  }
  //查询按钮点击事件
  async function handleSubmit() {
    let res = await validateFields();
    try {
      getTableData(res);
    } catch {}
  }
  //写入值输入框校验
  function onInputBlur(record) {
    console.log(record);
    //写入布尔量，true或者false BOOL = 1；写入整形值：SHORT = 4,BYTE = 3,WORD = 5,DWORD = 6,INT = 7,写入浮点值：FLOAT = 8,写入字符串：STR = 11,
    if (
      record.DataType === 'BOOL' &&
      (record.WriteValue !== 'true' || record.WriteValue !== 'true')
    ) {
      createMessage.warning(t('数据类型为BOOL，只能输入true或false！'));
      record.WriteValue = '';
    }
    if (
      (record.DataType === 'SHORT' ||
        record.DataType === 'BYTE' ||
        record.DataType === 'WORD' ||
        record.DataType === 'INT') &&
      !isInteger(record.WriteValue)
    ) {
      createMessage.warning(t('请输入整数！'));
      record.WriteValue = '';
    }
    if (record.DataType === 'FLOAT' && !validateNumber(record.WriteValue)) {
      createMessage.warning(t('请输入数字类型！'));
      record.WriteValue = '';
    }
  }

  function isInteger(str) {
    const regex = /^-?\d+$|^0$/;
    return regex.test(str);
  }
  function validateNumber(input) {
    const regex = /^-?\d+(\.\d+)?$/;
    return regex.test(input);
  }
  //读取参数
  async function readParams() {
    let vres = await validateFields();
    const { DeviceName } = await getFieldsValue();
    try {
      loading.value = true;
      let res = await readdownloadtags([DeviceName]);
      tableData = res;
      loading.value = false;
    } catch {
      loading.value = false;
    }
  }
  //参数下发
  async function parameterIssued() {
    const { AssetCode, ModelCode, ModelName, TypeCode, TypeName, DeviceName } =
      await getFieldsValue();
    let params = {
      AssetCode: AssetCode, //设备编码
      DeviceName: DeviceName, //设备名称
      ModelCode: ModelCode, //型号编码
      ModelName: ModelName, //型号名称
      TypeCode: TypeCode, //类型编码
      TypeName: TypeName, //类型名称
      DownloadTags: [] as any, //下发列表
    };
    if (tableData.length !== 0) {
      tableData.forEach((item: any) => {
        if (item.WriteValue && item.WriteValue !== '') {
          params.DownloadTags.push(item);
        }
      });
    }
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '参数下发确认'),
      content: () =>
        h(
          'span',
          `确定需要执行本次发参数下发吗？请确认参数写入值是否正确？同时确认设备处于安全状态`,
        ),
      onOk: async () => {
        try {
          let res = await commanddownload([params]);
          //下发完成重新获取设备参数
          getDownloadinfo(res);
        } catch (error) {}
      },
    });
  }
  //下发完成重新获取设备参数
  async function getDownloadinfo(res) {
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '下发完成'),
      content: () => h('span', `是否需要读取设备参数`),
      onOk: async () => {
        loading.value = true;
        try {
          let list = await afterdownloadinfo([res]);
          tableData = list.DownloadTags;
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }

  // 获取设备集合
  async function getTableData(params = {}) {
    clearSelectedRowKeys();
    try {
      loading.value = true;
      let res = await getalarmrecord([
        {
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      tableData = res.Items;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //导出参数
  async function handleDownLoad() {
    if(tableData.length === 0){
      createMessage.warning(t('请先读取参数！'));
      return;
    }
    const { AssetCode, ModelCode, ModelName, TypeCode, TypeName, DeviceName } =
      await getFieldsValue();
    let params = {
      AssetCode: AssetCode, //设备编码
      DeviceName: DeviceName, //设备名称
      ModelCode: ModelCode, //型号编码
      ModelName: ModelName, //型号名称
      TypeCode: TypeCode, //类型编码
      TypeName: TypeName, //类型名称
      DownloadTags: tableData, //下发列表
    };
    let res = await handledownLoad([params]);
    const blob = new Blob([res.data], { type: 'application/octet-stream' });
    let hash = await getFileHash(blob);
    let resHash = res.headers['FileSHA'] || res.headers['filesha'] || '';

    if (hash === resHash) {
      downloadByData(res.data, '设备参数.xlsx');
    } else {
      createMessage.warning('文件数据缺失，请重新下载');
    }
  }

  //导入参数
  function handleImport() {
    if(tableData.length === 0){
      createMessage.warning(t('请先读取参数！'));
      return;
    }
    openModalByupload()

  }
  // 上传成功
  async function handleUploadSuccess(data) {
    closeModalByupload();
    //获取导入数据合并
    await handleMergedata(data)
  }
  async function handleMergedata(data){
    const { AssetCode, ModelCode, ModelName, TypeCode, TypeName, DeviceName } =
      await getFieldsValue();
      let params = {
        Source:{
          AssetCode: AssetCode, //设备编码
          DeviceName: DeviceName, //设备名称
          ModelCode: ModelCode, //型号编码
          ModelName: ModelName, //型号名称
          TypeCode: TypeCode, //类型编码
          TypeName: TypeName, //类型名称
          DownloadTags: tableData, //下发列表
        },
        Import:data
      };
      loading.value = true;
        try {
          let res = await mergedata([params]);
          tableData = res.DownloadTags;
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
    

  }

  onMounted(async () => {
    getDeviceTypes();
    getDeviceModels();
    getDriverinfo();
  });
</script>
<script lang="ts">
  export default {
    name: 'EquipmentLedgerIndexPage',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .search-box {
        display: flex;
        align-items: center;

        > .ant-btn-sm {
          height: 32px;
        }
      }

      .main-nav {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 240px;
        height: calc(100%);
        padding: 8px;
        box-sizing: border-box;
        overflow: auto;
        border-right: 1px solid #ccc;

        ::v-deep(.vben-tree__title) {
          user-select: none !important;
        }
      }

      .main-sidebar {
        position: absolute;
        top: 0;
        left: 240px;
        bottom: 0;
        width: 12px;
        border-radius: 5px;
        cursor: pointer;
        user-select: none;

        .close-btn {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12px;
          height: 30px;
          margin-top: -50%;

          line-height: 30px;
          text-align: center;
          background: #7dcdfe;
          border-radius: 6px;
          color: #fff;

          > span {
            font-size: 12px !important;
          }
        }
      }

      .main-sidebar:hover {
        background-color: #e2e3e5;
      }

      .main-content {
        position: relative;
        height: 100%;
        //margin-left: 260px;
        overflow: hidden;

        .pagination-box {
          z-index: 9;
          padding: 10px 5px;
          box-sizing: border-box;
          position: absolute;
          width: 100%;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: #fff;
        }
      }

      .main-content::after {
        content: '';
        display: block;
        width: 100%;
        height: 45px;
      }
    }

    .tag-nav-close {
      .main-nav {
        left: -260px;
      }

      .main-sidebar {
        left: 0;
      }

      .main-content {
        margin-left: 20px;
      }
    }
  }

  .form-box {
    padding: 5px;

    ::v-deep(.ant-form-item) {
      margin: 0 5px;
      margin-bottom: 8px;
    }
  }

  .red {
    color: red;
  }

  .green {
    color: green;
  }

  .gray {
    color: gray;
  }

  .blue {
    color: #0892f5;
  }
</style>
